/* 
  Copyright (c) SilverLining 2015
  Date:    2016-1-7
  File:    file_data.cpp  
  Description: 

*/

#include "stdafx.h"


using namespace m::alloc;
using namespace m::error;

namespace m
{
	namespace io
	{
		_file_data::_file_data()
			: Buffer(nullptr),
			Length(0),
			_Next(nullptr),
			_Prev(nullptr)
		{
		}

		_file_data::~_file_data()
		{
			if (Buffer)
			{
				delete[] Buffer;
			}

			// _Next and _Prev are "owned" by the FileState object they're
			// created for. Let it clean them up to avoid butchering
			// stack space.
		}

		void _file_data::initialize(const char *src, const size_t & length)
		{
			Clear();

			Buffer = new char[length];
			Length = length;
			if (length > 0)
			{
				assert(Buffer);
				if (Buffer)
				{
					memcpy_s(Buffer, length, src, length);
				}
			}
		}

		void _file_data::split(const size_t & countLeft, _file_data* RightBits)
		{
			assert(Buffer && countLeft <= Length);
			if (Buffer && countLeft <= Length)
			{
				size_t leftLength = countLeft;
				size_t rightLength = Length - countLeft;
				if (RightBits)
				{
					RightBits->initialize(Buffer + countLeft, rightLength);
				}
				Length = leftLength;
				char* NewBuffer = new char[Length];
				memcpy_s(NewBuffer, Length, Buffer, Length);
				delete[] Buffer;
				Buffer = NewBuffer;
			}
		}

		void _file_data::Clear()
		{
			if (Buffer)
			{
				delete[] Buffer;
				Buffer = nullptr;
			}
			Length = 0;
		}

		void* _file_data::operator new(size_t sz)
		{
			return ::operator new(sz, pool);
		}

		void _file_data::operator delete(void* ptr)
		{
			::operator delete(ptr, pool);
		}

	}
}